package com.wejoy.video.middle.station.api.filter;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.wejoy.video.middle.station.api.annotation.LoginCheck;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.util.LoginUtil;
import com.wejoy.video.middle.station.data.util.StringUtils;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.ReturnCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录过滤器
 * 用于将登录信息放到session中
 **/
@Order(1004)
@Configuration
public class LoginFilter implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    private final String NO_LOGIN_RETURN_INFO = JSON.toJSONString(RespJSON.returnCode(ReturnCode.NOT_LOGIN_ERROR));

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 将 options 请求放过
        String method = request.getMethod();
        if ("options".equalsIgnoreCase(method)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        LoginCheck loginCheckAnnotation = handlerMethod.getMethodAnnotation(LoginCheck.class);
        String userTokenHeader = request.getHeader("User-Token");
        SysUser loginUser;
        // 不需要登录的接口直接放过
        if (null == loginCheckAnnotation) {
            if (StringUtils.isEmpty(userTokenHeader)) {
                return true;
            }
            // 没有获取到用户信息 直接报错
            loginUser = LoginUtil.getLoginUser(userTokenHeader);

        } else {
            // 请求头没有token 直接报错
            if (StringUtils.isEmpty(userTokenHeader)) {
                returnNoLogin(response);
                return false;
            }
            // 没有获取到用户信息 直接报错
            loginUser = LoginUtil.getLoginUser(userTokenHeader);
            if (null == loginUser) {
                returnNoLogin(response);
                return false;
            }
        }

        // 用户信息保存到session
        SysUser finalLoginUser = loginUser;
        HttpSession session = request.getSession();
        session.setAttribute(LoginUtil.LOGIN_USER_SESSION_KEY, finalLoginUser);
        return true;
    }

    /**
     * 未登录时的返回内容
     * @param response
     * @return
     */
    private void returnNoLogin(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(NO_LOGIN_RETURN_INFO);
        } catch (IOException e) {
            logger.error(Throwables.getStackTraceAsString(e));
        } finally {
            writer.close();
        }
    }
}
